package com.example.layui_project.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.example.layui_project.comm.service.Impl.BaseServiceImpl;
import com.example.layui_project.dao.RoleDao;
import com.example.layui_project.dao.UserDao;
import com.example.layui_project.entity.SysRole;
import com.example.layui_project.entity.SysUser;
import com.example.layui_project.service.RoleService;
import com.example.layui_project.service.UserService;
import com.example.layui_project.utils.BestUitls;
import com.example.layui_project.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl extends BaseServiceImpl<SysRole> implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Override
    @Transactional
    public boolean add(SysRole role,String ids) {
        // 先添加一个权限信息'
        System.out.println(ids);
        Date date = new Date();
        role.setUpdateTime(date);
        role.setCreateTime(date);
        int i = roleDao.insertUseGeneratedKeys(role);
        if (i>0){
            List<Integer> idList = Arrays.asList(ids.replaceAll("\"","").split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
            // 然后批量添加数据
            int rowNum = roleDao.batchAdd(role, idList);
            return rowNum > 0 ? true : false;
        }
        return false;
    }
    @Override
    public boolean del(Integer id) {
        int i = roleDao.deleteByPrimaryKey(id);
        return i>0 ? true : false;
    }

    @Override
    @Transactional
    public boolean update(SysRole role,String ids) {
        int i = roleDao.updateByPrimaryKeySelective(role);
        if(i>0){
            int delRow = roleDao.removeAllRolePermission(role.getId());
            if (delRow>=0){
                ids = ids.replaceAll("\"", "");
                if(BestUitls.isNotBlank(ids)){
                    List<Integer> idList = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
                    // 然后批量添加数据
                    int rowNum = roleDao.batchAdd(role, idList);
                    return rowNum > 0 ? true : false;
                }else{
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public List<SysRole> getRoleAndPermissionByMenu() {
        return roleDao.getRoleAndPermissionByMenu();
    }

    @Override
    public List<SysRole> getAllRole() {
        List<SysRole> sysRoles = roleDao.selectAll();
        return sysRoles;
    }
}
